import $ from 'jquery'
export default{
  state: {
    id:"",
    username:"",
    photo:"",
    token:"",
    is_login:false
  },
  getters: {
  },
  mutations: {//存简单的
    updateUser(state,data){
      state.id = data.id;
      state.username = data.username;
      state.password = data.password;
      state.photo = data.photo;
      state.is_login = true;
    },
    updateToken(state,token){
      state.token = token;
    },
    logout(state){
      state.id = "";
      state.username = "";
      state.password = "";
      state.photo = "";
      state.is_login = false;
    }
  },
  actions: {//存复杂的
    //data通常包括用户的输入信息，比如username和password context提供了当前组件的上下文信息
    login(context,data){
      $.ajax({
        url:"http://localhost:3000/user/account/token/",
        type:"post",
        data:{
          username:data.username,
          password:data.password
        },
        success(resp){ //resp里面返回的都是后端service里面定义的
          if(resp.error_message==="success"){
            localStorage.setItem("jwt_token",resp.token);
            context.commit("updateToken",resp.token);//调用mutations中的updateToken方法,resp.token为传过去的数据
            data.success(resp);
          }else{
            data.error(resp);
          }
        },
        error(resp){
          data.error(resp);
        }
      });
    },
    getinfo(context,data){
      $.ajax({
        url:"http://localhost:3000/user/account/info/",
        type:"get",
        headers:{
          Authorization:"Bearer "+context.state.token,
        },
        success(resp){
          if(resp.error_message==="success"){
            context.commit("updateUser",{
              ...resp,//将resp解构出来（把数组或者类数组的对象展开成用，隔开的值）
              is_login:true,
            });
            
            data.success(resp);
          }else{
            data.error(resp);
          }  
        },
        error(resp){
          data.error(resp);
        }
      })
    },
    logout(context){ 
      localStorage.removeItem("jwt_token");
      context.commit("logout");
    }
  },
  modules: {
  }
}
